<template>
	<div>
		<div class="map-container">
			<svg :width="mapWidth" :height="mapHeight">
				<!-- 绘制所有点位图标 -->
				<image v-for="(point, index) in points" :key="index" :x="point.x - iconSize / 2"
					:y="point.y - iconSize / 2" :width="iconSize" :height="iconSize" :href="iconUrl" />
				<!-- 绘制轨迹路径 -->
				<path v-if="points.length > 1" :d="getPathD(points)" stroke="blue" stroke-width="2" fill="none"
					:stroke-dasharray="pathLength" :stroke-dashoffset="pathLength - animatedLength" />
			</svg>
		</div>
		<!-- 模拟添加点位的按钮 -->
		<button @click="addPoint({ x: 250, y: 250 })">添加点位</button>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted,
		watch
	} from 'vue';

	// 地图的宽度和高度
	const mapWidth = ref(300);
	const mapHeight = ref(300);
	// 存储所有点位的数组
	const points = ref([{
			x: 50,
			y: 50
		},
		{
			x: 100,
			y: 100
		},
		{
			x: 150,
			y: 150
		},
	]);
	// 路径的总长度和动画长度
	const pathLength = ref(0);
	const animatedLength = ref(0);
	// 图标相关
	const iconUrl = ref('/path/to/your/icon.png'); // 替换为实际的图标路径
	const iconSize = ref(20); // 图标大小

	// 添加点位的函数
	const addPoint = (point) => {
		points.value.push(point);
	};

	// 根据点位数组生成路径的 d 属性
	const getPathD = (pointsArray) => {
		if (pointsArray.length === 0) return '';
		let d = `M${pointsArray[0].x},${pointsArray[0].y}`;
		for (let i = 1; i < pointsArray.length; i++) {
			d += ` L${pointsArray[i].x},${pointsArray[i].y}`;
		}
		return d;
	};

	// 计算路径的长度
	const calculatePathLength = () => {
		if (points.value.length > 1) {
			const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
			path.setAttribute('d', getPathD(points.value));
			pathLength.value = path.getTotalLength();
			// 开始动画
			animatePath();
		}
	};

	// 动画函数，实现路径的动态绘制
	const animatePath = () => {
		let currentLength = 0;
		const interval = setInterval(() => {
			if (currentLength < pathLength.value) {
				currentLength += 2;
				animatedLength.value = currentLength;
			} else {
				clearInterval(interval);
			}
		}, 10);
	};

	// 监听点位数组的变化，重新计算路径长度
	watch(points, () => {
		calculatePathLength();
	});

	// 组件挂载后初始化路径长度
	onMounted(() => {
		calculatePathLength();
	});
</script>

<style scoped>
	.map-container {
		border: 1px solid #ccc;
	}
</style>